package com.example.vault.service;

import com.example.vault.annotation.DataSource;
import com.example.vault.config.DynamicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 支付业务服务
 * 演示多数据源在实际业务中的使用
 */
@Service
public class PaymentService {

    @Autowired
    @Qualifier("transactionJdbcTemplate")
    private JdbcTemplate transactionJdbcTemplate;

    @Autowired
    @Qualifier("userJdbcTemplate")
    private JdbcTemplate userJdbcTemplate;

    @Autowired
    @Qualifier("logJdbcTemplate")
    private JdbcTemplate logJdbcTemplate;

    /**
     * 创建支付订单（写操作 - 主库）
     */
    @DataSource(value = DynamicDataSource.DataSourceType.MASTER, database = "transaction")
    @Transactional("transactionTransactionManager")
    public Map<String, Object> createPaymentOrder(String userId, BigDecimal amount, String description) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 生成订单号
            String orderId = "PAY" + System.currentTimeMillis();
            
            // 模拟插入交易记录（实际项目中应该有对应的表结构）
            String sql = "SELECT ? as order_id, ? as user_id, ? as amount, ? as description, NOW() as create_time";
            Map<String, Object> order = transactionJdbcTemplate.queryForMap(sql, orderId, userId, amount, description);
            
            result.put("status", "success");
            result.put("message", "支付订单创建成功");
            result.put("order", order);
            
            // 记录操作日志
            logPaymentOperation("CREATE_ORDER", orderId, userId, "订单创建成功");
            
            return result;
        } catch (Exception e) {
            result.put("status", "error");
            result.put("message", "创建支付订单失败: " + e.getMessage());
            return result;
        }
    }

    /**
     * 查询支付订单（读操作 - 从库）
     */
    @DataSource(value = DynamicDataSource.DataSourceType.SLAVE, database = "transaction")
    public Map<String, Object> getPaymentOrder(String orderId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 模拟查询订单（从从库读取）
            String sql = "SELECT ? as order_id, 'USER001' as user_id, 100.00 as amount, '测试订单' as description, NOW() as create_time";
            Map<String, Object> order = transactionJdbcTemplate.queryForMap(sql, orderId);
            
            result.put("status", "success");
            result.put("message", "订单查询成功");
            result.put("order", order);
            
            return result;
        } catch (Exception e) {
            result.put("status", "error");
            result.put("message", "查询订单失败: " + e.getMessage());
            return result;
        }
    }

    /**
     * 查询用户信息（读操作 - 从库）
     */
    @DataSource(value = DynamicDataSource.DataSourceType.SLAVE, database = "user")
    public Map<String, Object> getUserInfo(String userId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 模拟查询用户信息
            String sql = "SELECT ? as user_id, '张三' as username, 'zhangsan@example.com' as email, NOW() as create_time";
            Map<String, Object> user = userJdbcTemplate.queryForMap(sql, userId);
            
            result.put("status", "success");
            result.put("message", "用户信息查询成功");
            result.put("user", user);
            
            return result;
        } catch (Exception e) {
            result.put("status", "error");
            result.put("message", "查询用户信息失败: " + e.getMessage());
            return result;
        }
    }

    /**
     * 更新用户信息（写操作 - 主库）
     */
    @DataSource(value = DynamicDataSource.DataSourceType.MASTER, database = "user")
    @Transactional("userTransactionManager")
    public Map<String, Object> updateUserInfo(String userId, String username, String email) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 模拟更新用户信息
            String sql = "SELECT ? as user_id, ? as username, ? as email, NOW() as update_time";
            Map<String, Object> user = userJdbcTemplate.queryForMap(sql, userId, username, email);
            
            result.put("status", "success");
            result.put("message", "用户信息更新成功");
            result.put("user", user);
            
            // 记录操作日志
            logPaymentOperation("UPDATE_USER", userId, userId, "用户信息更新成功");
            
            return result;
        } catch (Exception e) {
            result.put("status", "error");
            result.put("message", "更新用户信息失败: " + e.getMessage());
            return result;
        }
    }

    /**
     * 查询操作日志（读操作 - 从库）
     */
    @DataSource(value = DynamicDataSource.DataSourceType.SLAVE, database = "log")
    public Map<String, Object> getOperationLogs(String userId, int limit) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 模拟查询操作日志
            String sql = "SELECT 'LOG001' as log_id, ? as user_id, 'CREATE_ORDER' as operation, '订单创建' as description, NOW() as create_time";
            List<Map<String, Object>> logs = List.of(logJdbcTemplate.queryForMap(sql, userId));
            
            result.put("status", "success");
            result.put("message", "操作日志查询成功");
            result.put("logs", logs);
            result.put("count", logs.size());
            
            return result;
        } catch (Exception e) {
            result.put("status", "error");
            result.put("message", "查询操作日志失败: " + e.getMessage());
            return result;
        }
    }

    /**
     * 记录支付操作日志（写操作 - 主库）
     */
    @DataSource(value = DynamicDataSource.DataSourceType.MASTER, database = "log")
    @Transactional("logTransactionManager")
    public void logPaymentOperation(String operation, String orderId, String userId, String description) {
        try {
            // 模拟插入操作日志
            String sql = "SELECT ? as operation, ? as order_id, ? as user_id, ? as description, NOW() as create_time";
            logJdbcTemplate.queryForMap(sql, operation, orderId, userId, description);
        } catch (Exception e) {
            // 日志记录失败不应该影响主业务
            System.err.println("记录操作日志失败: " + e.getMessage());
        }
    }

    /**
     * 复合业务操作：创建订单并更新用户状态
     * 演示跨数据源事务处理
     */
    public Map<String, Object> createOrderAndUpdateUser(String userId, BigDecimal amount, String description) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 1. 创建支付订单（交易库）
            Map<String, Object> orderResult = createPaymentOrder(userId, amount, description);
            
            if (!"success".equals(orderResult.get("status"))) {
                return orderResult;
            }
            
            // 2. 更新用户信息（用户库）
            Map<String, Object> userResult = updateUserInfo(userId, "更新用户", "updated@example.com");
            
            if (!"success".equals(userResult.get("status"))) {
                result.put("status", "partial_success");
                result.put("message", "订单创建成功，但用户信息更新失败");
                result.put("order", orderResult.get("order"));
                result.put("userError", userResult.get("message"));
                return result;
            }
            
            // 3. 记录综合操作日志
            logPaymentOperation("CREATE_ORDER_AND_UPDATE_USER", 
                ((Map<String, Object>) orderResult.get("order")).get("order_id").toString(), 
                userId, "创建订单并更新用户信息成功");
            
            result.put("status", "success");
            result.put("message", "订单创建和用户更新都成功");
            result.put("order", orderResult.get("order"));
            result.put("user", userResult.get("user"));
            
            return result;
        } catch (Exception e) {
            result.put("status", "error");
            result.put("message", "复合操作失败: " + e.getMessage());
            return result;
        }
    }

    /**
     * 获取支付统计信息（读操作 - 从库）
     * 演示复杂查询在从库执行
     */
    @DataSource(value = DynamicDataSource.DataSourceType.SLAVE, database = "transaction")
    public Map<String, Object> getPaymentStatistics() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 模拟统计查询
            String sql = "SELECT 100 as total_orders, 50000.00 as total_amount, 95.5 as success_rate, NOW() as stat_time";
            Map<String, Object> stats = transactionJdbcTemplate.queryForMap(sql);
            
            result.put("status", "success");
            result.put("message", "支付统计查询成功");
            result.put("statistics", stats);
            
            return result;
        } catch (Exception e) {
            result.put("status", "error");
            result.put("message", "查询支付统计失败: " + e.getMessage());
            return result;
        }
    }
}